<template>
  <div>
    <v-container>
      <v-row>
        <v-col>
          <v-expansion-panels multiple popout>
            <v-expansion-panel v-for="(drawer, i) in drawerList" :key="i">
              <v-expansion-panel-header>
                {{ drawer.name }}
              </v-expansion-panel-header>
              <v-expansion-panel-content>
                <v-row justify="space-around" no-gutters>
                  <v-col>
                    <template>
                      <v-simple-table>
                        <template v-slot:default>
                          <thead>
                            <tr>
                              <th class="text-left">类型</th>
                              <th class="text-left">名称</th>
                              <th class="text-left">标识码</th>
                              <th class="text-left">状态</th>
                              <th class="text-left">最后借出人</th>
                              <th class="text-left">最后借出时间</th>
                              <th class="text-left">动作</th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr
                              v-for="item in toolList.filter(
                                (itemToFilter) =>
                                  itemToFilter.drawer == drawer.id
                              )"
                              :key="item.id"
                            >
                              <td>
                                {{
                                  toolTypes.find(
                                    (itemToFind) => itemToFind.id == item.type
                                  ).name
                                }}
                              </td>
                              <td>{{ item.name }}</td>
                              <td>{{ item.identifier }}</td>
                              <td>
                                {{
                                  item.state == 0
                                    ? "借出"
                                    : item.state == 1
                                    ? "在库"
                                    : "丢失"
                                }}
                              </td>
                              <td v-if="item.state == 0">
                                {{
                                  userList.find(
                                    (itemToFind) =>
                                      itemToFind.id == item.lastLendedUserId
                                  ).name
                                }}
                              </td>
                              <td v-else>-</td>
                              <td v-if="item.state == 0">
                                {{ item.lastLendedTime }}
                              </td>
                              <td v-else>-</td>
                              <td>
                                <v-btn
                                  :disabled="pendingPopOut"
                                  :loading="pendingPopOut"
                                  color="primary"
                                  @click="
                                    pendingPopOut = true;
                                    popOutByToolId(item.id);
                                  "
                                >
                                  弹开
                                </v-btn>
                              </td>
                            </tr>
                          </tbody>
                        </template>
                      </v-simple-table>
                    </template>
                  </v-col>
                </v-row>
                <v-row>
                  <v-col class="text-right">
                    <v-btn
                      :disabled="pendingPopOut"
                      :loading="pendingPopOut"
                      color="primary"
                      @click="
                        pendingPopOut = true;
                        popOutByDrawerNo(drawer.no);
                      "
                    >
                      弹开
                    </v-btn>
                  </v-col>
                </v-row>
              </v-expansion-panel-content>
            </v-expansion-panel>
          </v-expansion-panels>
        </v-col>
      </v-row>
      <v-row>
        <v-col>
          <v-card>
            <v-card-title>盘存</v-card-title>
            <v-alert
              outlined
              type="warning"
              prominent
              border="left"
              v-model="stocking"
            >
              请将要盘存的工具放在射频信号接收区...
            </v-alert>
            <v-card-actions>
              <v-btn
                color="primary"
                :disabled="stocking || scanning"
                @click="startStocking"
              >
                开始
              </v-btn>
              <v-btn
                color="primary"
                :disabled="!stocking || scanning"
                @click="stopStocking"
              >
                停止
              </v-btn>
            </v-card-actions>
          </v-card>
        </v-col>
      </v-row>
      <v-row>
        <v-col>
          <v-btn
            color="primary"
            :disabled="stocking || scanning"
            :loading="scanning"
            @click="startInventory"
            >一键盘点</v-btn
          >
        </v-col>
      </v-row>
      <v-row>
        <v-col>
          <v-btn
            color="primary"
            :disabled="pendingPopOut"
            :loading="pendingPopOut"
            @click="
              pendingPopOut = true;
              popOutAll();
            "
            >一键弹开</v-btn
          >
        </v-col>
      </v-row>
      <v-row>
        <v-col>
          <v-btn
            color="primary"
            :disabled="pendingGetBatteryInfo"
            :loading="pendingGetBatteryInfo"
            @click="
              pendingGetBatteryInfo = true;
              getBatteryInfo();
            "
            >获取电池信息</v-btn
          >
        </v-col>
      </v-row>
      <v-row>
        <v-col>
          <v-snackbar
            v-if="!failed"
            v-model="alert"
            :timeout="3000"
            color="success"
          >
            {{ info }}
          </v-snackbar>
          <v-snackbar v-else v-model="alert">
            {{ info }}

            <template v-slot:action="{ attrs }">
              <v-btn color="red" text v-bind="attrs" @click="alert = false">
                关闭
              </v-btn>
            </template>
          </v-snackbar>
        </v-col>
      </v-row>
    </v-container>
    <v-dialog v-model="dialogScanResult" max-width="600">
      <v-card class="pa-6">
        <v-container>
          <v-row>
            <v-col>
              <v-list>
                <v-subheader>存放的工具</v-subheader>
                <v-list-item
                  v-for="(item, i) in scanResult.toolsAdded"
                  :key="i"
                  two-line
                >
                  <v-list-item-content>
                    <v-list-item-title>
                      {{
                        toolTypes.find(
                          (itemToFind) =>
                            itemToFind.id ==
                            toolList.find(
                              (itemToFind) => itemToFind.identifier == item
                            ).type
                        ).name
                      }}
                    </v-list-item-title>
                    <v-list-item-subtitle>
                      {{
                        toolList.find(
                          (itemToFind) => itemToFind.identifier == item
                        ).name
                      }}
                    </v-list-item-subtitle>
                  </v-list-item-content>
                </v-list-item>
              </v-list>
            </v-col>
            <v-col>
              <v-list>
                <v-subheader>借出的工具</v-subheader>
                <v-list-item
                  v-for="(item, i) in scanResult.toolsRemoved"
                  :key="i"
                  two-line
                >
                  <v-list-item-content>
                    <v-list-item-title>
                      {{
                        toolTypes.find(
                          (itemToFind) =>
                            itemToFind.id ==
                            toolList.find(
                              (itemToFind) => itemToFind.identifier == item
                            ).type
                        ).name
                      }}
                    </v-list-item-title>
                    <v-list-item-subtitle>
                      {{
                        toolList.find(
                          (itemToFind) => itemToFind.identifier == item
                        ).name
                      }}
                    </v-list-item-subtitle>
                  </v-list-item-content>
                </v-list-item>
              </v-list>
            </v-col>
          </v-row>
        </v-container>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="deep-purple lighten-2"
            text
            @click="dialogScanResult = false"
          >
            确定
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-dialog v-model="dialogInventoryResult" max-width="600">
      <v-card class="pa-6">
        <v-container>
          <v-row>
            <v-col>
              <v-list>
                <v-subheader>在管</v-subheader>
                <v-list-item
                  v-for="(item, i) in inventoryResult.toolsInDB"
                  :key="i"
                  two-line
                >
                  <v-list-item-content>
                    <v-list-item-title>
                      {{
                        toolTypes.find(
                          (itemToFind) =>
                            itemToFind.id ==
                            toolList.find(
                              (itemToFind) => itemToFind.identifier == item
                            ).type
                        ).name
                      }}
                    </v-list-item-title>
                    <v-list-item-subtitle>
                      {{
                        toolList.find(
                          (itemToFind) => itemToFind.identifier == item
                        ).name
                      }}
                    </v-list-item-subtitle>
                  </v-list-item-content>
                </v-list-item>
              </v-list>
            </v-col>
            <v-col>
              <v-list>
                <v-subheader>在库</v-subheader>
                <v-list-item
                  v-for="(item, i) in inventoryResult.toolsInPosition"
                  :key="i"
                  two-line
                >
                  <v-list-item-content>
                    <v-list-item-title>
                      {{
                        toolTypes.find(
                          (itemToFind) =>
                            itemToFind.id ==
                            toolList.find(
                              (itemToFind) => itemToFind.identifier == item
                            ).type
                        ).name
                      }}
                    </v-list-item-title>
                    <v-list-item-subtitle>
                      {{
                        toolList.find(
                          (itemToFind) => itemToFind.identifier == item
                        ).name
                      }}
                    </v-list-item-subtitle>
                  </v-list-item-content>
                </v-list-item>
              </v-list>
            </v-col>
          </v-row>
          <v-row>
            <v-col>
              <v-list>
                <v-subheader>借出</v-subheader>
                <v-list-item
                  v-for="(item, i) in inventoryResult.toolsDispensed"
                  :key="i"
                  two-line
                >
                  <v-list-item-content>
                    <v-list-item-title>
                      {{
                        toolTypes.find(
                          (itemToFind) =>
                            itemToFind.id ==
                            toolList.find(
                              (itemToFind) => itemToFind.identifier == item
                            ).type
                        ).name
                      }}
                    </v-list-item-title>
                    <v-list-item-subtitle>
                      {{
                        toolList.find(
                          (itemToFind) => itemToFind.identifier == item
                        ).name
                      }}
                    </v-list-item-subtitle>
                  </v-list-item-content>
                </v-list-item>
              </v-list>
            </v-col>
            <v-col>
              <v-list>
                <v-subheader>丢失</v-subheader>
                <v-list-item
                  v-for="(item, i) in inventoryResult.toolsLosed"
                  :key="i"
                  two-line
                >
                  <v-list-item-content>
                    <v-list-item-title>
                      {{
                        toolTypes.find(
                          (itemToFind) =>
                            itemToFind.id ==
                            toolList.find(
                              (itemToFind) => itemToFind.identifier == item
                            ).type
                        ).name
                      }}
                    </v-list-item-title>
                    <v-list-item-subtitle>
                      {{
                        toolList.find(
                          (itemToFind) => itemToFind.identifier == item
                        ).name
                      }}
                    </v-list-item-subtitle>
                  </v-list-item-content>
                </v-list-item>
              </v-list>
            </v-col>
          </v-row>
          <v-row>
            <v-col>
              <v-list>
                <v-subheader>串入</v-subheader>
                <v-list-item
                  v-for="(item, i) in inventoryResult.toolsStealedIn"
                  :key="i"
                  two-line
                >
                  <v-list-item-content>
                    <v-list-item-title> 未知 </v-list-item-title>
                    <v-list-item-subtitle>
                      {{ item }}
                    </v-list-item-subtitle>
                  </v-list-item-content>
                </v-list-item>
              </v-list>
            </v-col>
          </v-row>
        </v-container>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="deep-purple lighten-2"
            text
            @click="dialogInventoryResult = false"
          >
            关闭
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-dialog v-model="dialogCloseTimeout" persistent max-width="290">
      <v-card>
        <v-card-title class="text-h6 text-center">
          拿取/存放工具完毕后，请您尽快合上柜门！
        </v-card-title>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="primary" text @click="dialogCloseTimeout = false">
            确定
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-dialog v-model="dialogPopOutAllErrInfo" max-width="600">
      <v-card class="pa-6">
        <v-container>
          <v-row>
            <v-col>
              <v-list>
                <v-subheader>一键弹出结果</v-subheader>
                <v-list-item
                  v-for="(item, i) in popOutAllFailDetail"
                  :key="i"
                  two-line
                >
                  <v-list-item-content>
                    <v-list-item-title>
                      抽屉编号：{{ item.drawerNo }}
                    </v-list-item-title>
                    <v-list-item-subtitle>
                      异常信息：{{ item.errInfo }}
                    </v-list-item-subtitle>
                  </v-list-item-content>
                </v-list-item>
              </v-list>
            </v-col>
          </v-row>
        </v-container>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="deep-purple lighten-2"
            text
            @click="dialogPopOutAllErrInfo = false"
          >
            关闭
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-dialog v-model="dialogLendedToolsExpired" max-width="600">
      <v-card class="pa-6">
        <v-container>
          <v-row>
            <v-col>
              <v-list>
                <v-header
                  >未归还的工具
                  <v-badge
                    color="info"
                    :content="lendedToolsExpires.length"
                    inline
                  ></v-badge>
                </v-header>
                <v-list-item v-for="(item, i) in lendedToolsExpires" :key="i">
                  <v-list-item-content>
                    <div>工具类型：{{ item.toolTypeName }}</div>
                    <div>工具名称：{{ item.toolName }}</div>
                    <div>所在抽屉：{{ item.drawName }}</div>
                    <div>最后借出人：{{ item.lastLendedUser }}</div>
                    <div>最后借出时间：{{ item.lastLendedTime }}</div>
                  </v-list-item-content>
                </v-list-item>
              </v-list>
            </v-col>
          </v-row>
        </v-container>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="deep-purple lighten-2"
            text
            @click="dialogLendedToolsExpired = false"
          >
            关闭
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-dialog v-model="dialogScanning" persistent max-width="290">
      <v-card>
        <v-card-title class="text-h6 text-center">
          正在盘点，请稍后...
        </v-card-title>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
export default {
  data: () => ({
    scanResult: {
      toolsAdded: [],
      toolsRemoved: [],
    },

    inventoryResult: {
      toolsInDB: [],
      toolsInPosition: [],
      toolsDispensed: [],
      toolsLosed: [],
      toolsStealedIn: [],
    },

    batteryInfo: {
      inCharging: false,
      batteryLevel: 100,
    },

    popOutAllFailDetail: [],

    drawerList: [
      {
        id: 1,
        name: "抽屉一",
        no: 1,
      },
      {
        id: 2,
        name: "抽屉二",
        no: 2,
      },
      {
        id: 3,
        name: "抽屉三",
        no: 3,
      },
    ],
    toolTypes: [
      {
        id: 1,
        name: "钳子",
      },
      {
        id: 2,
        name: "改锥",
      },
      {
        id: 3,
        name: "扳手",
      },
    ],
    userList: [
      {
        id: 1,
        type: 2,
        name: "Admin",
        label: null,
        seqNum: null,
        password: null,
      },
      {
        id: 2,
        type: 1,
        name: "刘康",
        label: null,
        seqNum: null,
        password: null,
      },
    ],
    toolList: [
      {
        id: 1,
        type: 1,
        name: "尖嘴钳",
        drawer: 1,
        identifier: "AA",
        state: 1,
        lastLendedUserId: null,
        lastLendedTime: null,
      },

      {
        id: 2,
        type: 2,
        name: "十字改锥",
        drawer: 1,
        identifier: "BB",
        state: 1,
        lastLendedUserId: null,
        lastLendedTime: null,
      },
      {
        id: 3,
        type: 3,
        name: "14mm",
        drawer: 1,
        identifier: "CC",
        state: 0,
        lastLendedUserId: 1,
        lastLendedTime: "2024-03-11 20:18:55.147",
      },
      {
        id: 4,
        type: 1,
        name: "斜口钳",
        drawer: 2,
        identifier: "DD",
        state: 1,
        lastLendedUserId: null,
        lastLendedTime: null,
      },
      {
        id: 5,
        type: 2,
        name: "一字改锥",
        drawer: 2,
        identifier: "EE",
        state: 1,
        lastLendedUserId: null,
        lastLendedTime: null,
      },
      {
        id: 6,
        type: 3,
        name: "16mm",
        drawer: 2,
        identifier: "FF",
        state: 1,
        lastLendedUserId: null,
        lastLendedTime: null,
      },
      {
        id: 7,
        type: 1,
        name: "管钳",
        drawer: 3,
        identifier: "GG",
        state: 1,
        lastLendedUserId: null,
        lastLendedTime: null,
      },
      {
        id: 8,
        type: 2,
        name: "星型改锥",
        drawer: 3,
        identifier: "HH",
        state: 1,
        lastLendedUserId: null,
        lastLendedTime: null,
      },
      {
        id: 9,
        type: 3,
        name: "梅花扳手",
        drawer: 3,
        identifier: "II",
        state: 1,
        lastLendedUserId: null,
        lastLendedTime: null,
      },
    ],
    lendedToolsExpires: [],
    alert: false,
    info: "",
    failed: false,
    dialogScanResult: false,
    dialogInventoryResult: false,
    dialogCloseTimeout: false,
    dialogPopOutAllErrInfo: false,
    dialogScanning: false,
    dialogLendedToolsExpired: false,
    pendingPopOut: false,
    pendingGetBatteryInfo: false,
    scanning: false,
    stocking: false,
  }),

  methods: {
    popOutByDrawerNo(drawerNo) {
      this.toolDispense.popOutByDrawerNo(drawerNo);
    },
    popOutByToolId(toolId) {
      this.toolDispense.popOutByToolId(toolId);
    },
    popOutAll() {
      this.toolDispense.popOutAll();
    },

    startStocking() {
      this.toolDispense.stopDetect();
      this.toolDispense.startStocking();
      this.stocking = true;
    },
    stopStocking() {
      this.toolDispense.stopStocking();
      this.stocking = false;
      this.toolDispense.startDetect();
    },

    startInventory() {
      this.toolDispense.startInventory();
      this.scanning = true;
      this.dialogScanning = true;
    },

    getBatteryInfo() {
      this.toolDispense.getBatteryInfo();
    },
    onPoppedOut(succeed, errInfo) {
      if (succeed) {
        this.pendingPopOut = false;

        this.info = "弹出成功";
        this.failed = false;
        this.alert = true;

        this.toolDispense.startScan();
        this.scanning = true;
      } else {
        this.pendingPopOut = false;

        this.info = "弹出失败，原因：" + errInfo;
        this.failed = true;
        this.alert = true;
      }
    },
    onAllPoppedOut(succeed, errInfoList) {
      if (succeed) {
        this.pendingPopOut = false;

        this.info = "全部弹出成功";
        this.failed = false;
        this.alert = true;

        this.toolDispense.startScan();
        this.scanning = true;
      } else {
        this.pendingPopOut = false;

        this.info = "全部弹出失败";
        this.failed = true;
        this.alert = true;

        this.popOutAllFailDetail = JSON.parse(errInfoList);
        this.dialogPopOutAllErrInfo = true;
      }
    },
    onScanned(succeed, resultOrErrInfo) {
      this.scanning = false;
      this.dialogScanning = false;

      if (succeed) {
        this.scanResult = JSON.parse(resultOrErrInfo);
        this.dialogScanResult = true;

        this.toolManage
          .getToolList()
          .then((retVal) => (this.toolList = JSON.parse(retVal)));
      } else {
        this.info = "扫描失败，原因：" + resultOrErrInfo;
        this.failed = true;
        this.alert = true;
      }
    },
    onInventoried(succeed, resultOrErrInfo) {
      this.scanning = false;
      this.dialogScanning = false;

      if (succeed) {
        this.inventoryResult = JSON.parse(resultOrErrInfo);
        this.dialogInventoryResult = true;

        this.toolManage
          .getToolList()
          .then((retVal) => (this.toolList = JSON.parse(retVal)));
      } else {
        this.info = "盘点失败，原因：" + resultOrErrInfo;
        this.failed = true;
        this.alert = true;
      }
    },
    onDrawerClosed() {
      this.dialogCloseTimeout = false;
      this.dialogScanning = true;
    },
    onDrawerCloseTimeout() {
      this.dialogCloseTimeout = true;
    },
    onStocked(succeed, resultOrErrInfo) {
      if (succeed) {
        this.info =
          "盘存成功，工具为：" +
          this.toolTypes.find(
            (item) =>
              item.id ==
              this.toolList.find((item) => item.identifier == resultOrErrInfo)
                .type
          ).name +
          "--" +
          this.toolList.find((item) => item.identifier == resultOrErrInfo)
            .name +
          "[" +
          resultOrErrInfo +
          "]";
        this.failed = false;
        this.alert = true;

        this.toolManage
          .getToolList()
          .then((retVal) => (this.toolList = JSON.parse(retVal)));
      } else {
        this.info = "盘存失败，原因：" + resultOrErrInfo;
        this.failed = true;
        this.alert = true;
      }
    },
    onBatteryInfoGot(succeed, resultOrErrInfo) {
      if (succeed) {
        this.pendingGetBatteryInfo = false;

        this.batteryInfo = JSON.parse(resultOrErrInfo);
        this.info =
          "是否正在充电：" +
          this.batteryInfo.inCharging +
          "，电量（百分比）：" +
          this.batteryInfo.batteryLevel;
        this.failed = true;
        this.alert = true;
      } else {
        this.pendingGetBatteryInfo = false;

        this.info = "查询电池信息失败，原因：" + resultOrErrInfo;
        this.failed = true;
        this.alert = true;
      }
    },
  },

  mounted: async function () {
    this.toolDispense.poppedOut.connect(this.onPoppedOut);
    this.toolDispense.allPoppedOut.connect(this.onAllPoppedOut);
    this.toolDispense.scanned.connect(this.onScanned);
    this.toolDispense.inventoried.connect(this.onInventoried);
    this.toolDispense.drawerClosed.connect(this.onDrawerClosed);
    this.toolDispense.drawerCloseTimeout.connect(this.onDrawerCloseTimeout);
    this.toolDispense.stocked.connect(this.onStocked);
    this.toolDispense.batteryInfoGot.connect(this.onBatteryInfoGot);

    this.toolTypes = JSON.parse(await this.toolManage.getToolTypes());
    this.drawerList = JSON.parse(await this.toolManage.getDrawerList());
    this.userList = JSON.parse(await this.userManage.getUserList());
    this.toolList = JSON.parse(await this.toolManage.getToolList());
    this.lendedToolsExpires = JSON.parse(
      await this.toolDispense.getLendedToolsExpires()
    );
    this.dialogLendedToolsExpired = this.lendedToolsExpires.length > 0;

    this.toolDispense.startDetect(); //开启工具检测服务————检测到工具时自动开启相应的抽屉
  },

  unmounted: function () {
    this.toolDispense.poppedOut.disconnect(this.onPoppedOut);
    this.toolDispense.allPoppedOut.disconnect(this.onAllPoppedOut);
    this.toolDispense.scanned.disconnect(this.onScanned);
    this.toolDispense.inventoried.disconnect(this.onInventoried);
    this.toolDispense.drawerClosed.disconnect(this.onDrawerClosed);
    this.toolDispense.drawerCloseTimeout.disconnect(this.onDrawerCloseTimeout);
    this.toolDispense.stocked.disconnect(this.onStocked);
    this.toolDispense.batteryInfoGot.disconnect(this.onBatteryInfoGot);

    this.toolDispense.stopDetect();
    this.toolDispense.stopStocking();
  },
};
</script>
